import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.UUID;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class YoudaoISEAPI {

    // 需要修改的部分：设置你的应用ID和应用密钥
    private static final String APP_KEY = "3ef8c60c6c29e3jd"; // 替换为你的有道云应用ID
    private static final String APP_SECRET = "DXaOjr97ySabHPQr1KpLBOykVVGbM75f"; // 替换为你的有道云应用密钥

    // 有道云API的URL
    private static final String YOUDAO_URL = "https://openapi.youdao.com/iseapi";

    public static void main(String[] args) {
        // 需要修改的部分：设置音频文件路径和对应的文字
        String audioFilePath = "音频的路径"; // 替换为你的音频文件路径
        String text = "en"; // 替换为音频对应的文字

        // 调用API
        String result = connect(audioFilePath, text);
        System.out.println(result);
    }

    public static String connect(String audioFilePath, String text) {
        // 检查音频文件格式
        if (!audioFilePath.endsWith(".wav")) {
            System.out.println("不支持的音频类型，仅支持WAV格式");
            return null;
        }

        try {
            // 读取音频文件并编码为Base64
            File audioFile = new File(audioFilePath);
            byte[] audioBytes = new byte[(int) audioFile.length()];
            try (FileInputStream fis = new FileInputStream(audioFile)) {
                fis.read(audioBytes);
            }
            String q = Base64.getEncoder().encodeToString(audioBytes);

            // 获取音频文件的采样率和声道数
            int sampleRate = 16000; // 默认采样率，需根据实际文件修改
            int nchannels = 1; // 默认单声道，需根据实际文件修改

            // 构造请求数据
            String curtime = String.valueOf(System.currentTimeMillis() / 1000);
            String salt = UUID.randomUUID().toString();
            String signStr = APP_KEY + truncate(q) + salt + curtime + APP_SECRET;
            String sign = encrypt(signStr);

            // 创建HTTP POST请求
            HttpPost httpPost = new HttpPost(YOUDAO_URL);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addTextBody("text", text, ContentType.TEXT_PLAIN);
            builder.addTextBody("curtime", curtime, ContentType.TEXT_PLAIN);
            builder.addTextBody("appKey", APP_KEY, ContentType.TEXT_PLAIN);
            builder.addTextBody("q", q, ContentType.TEXT_PLAIN);
            builder.addTextBody("salt", salt, ContentType.TEXT_PLAIN);
            builder.addTextBody("sign", sign, ContentType.TEXT_PLAIN);
            builder.addTextBody("signType", "v2", ContentType.TEXT_PLAIN);
            builder.addTextBody("langType", "en", ContentType.TEXT_PLAIN); // 语言类型，默认为英文
            builder.addTextBody("rate", String.valueOf(sampleRate), ContentType.TEXT_PLAIN);
            builder.addTextBody("format", "wav", ContentType.TEXT_PLAIN);
            builder.addTextBody("channel", String.valueOf(nchannels), ContentType.TEXT_PLAIN);
            builder.addTextBody("type", "1", ContentType.TEXT_PLAIN);

            httpPost.setEntity(builder.build());

            // 发送请求并获取响应
            try (CloseableHttpClient httpClient = HttpClients.createDefault();
                 CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String truncate(String q) {
        if (q == null) {
            return null;
        }
        int size = q.length();
        return size <= 20 ? q : q.substring(0, 10) + size + q.substring(size - 10);
    }

    private static String encrypt(String signStr) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(signStr.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
}